import db from '@/mock/createDB'
import Mock from 'mockjs'
import jwt from 'jsonwebtoken'
import md5 from 'js-md5'

// 用户列表分页查询
Mock.mock('/users/query', 'post', ({ body }) => {
  // 验证token,这里拿不到header里的，假装用本地的，真实必须请求传过来的
  const token = localStorage.getItem('token')
   return jwt.verify(token,'zhiyuanzuishuai',(err,decode)=>{
     if(err) {
      return { code: 1000, message: 'token失效,请重新登陆'}
     }else {
      const userName = decode.data;
      let {pageNo, pageSize, name, status} = JSON.parse(body);
      // 数字的转为数字
      pageNo = +pageNo;
      pageSize = +pageSize;
      status = +status;
      // 处理中文乱码问题
      name = name ? decodeURIComponent(name) : name;
      
      // 先搜索（模糊搜索）(除掉自己)
      const searchResult = db.select('users_table', (item:any) => {
        return (item.name.includes(name) || !name) && (item.status === status || !status) && item.userName !== userName;
      })

      // 后分页
      const total = searchResult.length;
      const totalPage = Math.ceil(total / pageSize);
      if (pageNo > totalPage) pageNo = totalPage;
      const start = (pageNo - 1) * pageSize;
      const end = start + pageSize;
      // 搜索的结果切合分页
      const pageResult = searchResult.slice(start, end);
      return { code: 0, message: '查询成功', data: {pageNo, pageSize, total, dataLists:pageResult} }
     }
   })
})

// 所有用户查询
Mock.mock('/users/all', 'get', () => {
  const result = db.select('users_table', (item:any) => {
    return true;
  })
  return { code: 0, message: '查询成功', data: result }
})

// 添加用户
Mock.mock('/users/create', 'post', ({ body }) => {
  let { userName, password, name, roleId, phoneNum, avatar, departmentId, email, status = 2 } = JSON.parse(body)
  // 数字的转为数字
  roleId = +roleId;
  departmentId = +departmentId;
  status = +status;
  const nameRepeat = db.select('users_table', (item:any) => item.userName === userName)
  // 判断用户名是否存在
  if (nameRepeat && nameRepeat.length) {
    return {
      code: 1003,
      message: '该账号已被注册,请重新输入账号'
    }
  }
  const mobileRepeat = db.select('users_table', (item:any) => item.phoneNum === phoneNum && phoneNum)
  // 判断手机号是否被使用
  if (mobileRepeat && mobileRepeat.length) {
    return {
      code: 1004,
      message: '手机号码已经被注册，请重新输入'
    }
  }
  db.add('users_table', { userName, password, name, roleId, phoneNum, avatar, departmentId, email, status })
  // 部门人数加一
  const currentDepart = db.select('departments_table', item => item.id === departmentId)[0];
  const {members:_members} = currentDepart;
  db.put('departments_table', departmentId, {members: _members+1})
  return {
    code: 0,
    message: '添加成功'
  }
})

// 修改用户
Mock.mock('/users/modify', 'post', ({ body }) => {
  let { id, userName,  name, roleId, phoneNum, avatar, departmentId, email, status = 0 } = JSON.parse(body);
  // 数字的转为数字
  id = +id;
  roleId = +roleId;
  departmentId = +departmentId;
  status = +status;
  const result = db.select('users_table', item => item.id === id)[0];
  const { phoneNum: _phoneNum, departmentId:_departmentId } = result;
  const mobileRepeat = db.select('users_table', (item:any) => item.phoneNum === phoneNum && item.phoneNum !== _phoneNum && phoneNum);
  // 判断手机号是否被使用
  if (mobileRepeat && mobileRepeat.length) {
    return {
      code: 1004,
      message: '手机号码已经被注册，请重新输入'
    }
  }
  const row = {id, userName,  name, roleId, phoneNum, avatar, departmentId, email, status}
  db.put('users_table', id, row)
  // 当部门改变时，修改部门人数,原部门减少1，新部门加1
  if( _departmentId !== departmentId ) {
    const oldDepart = db.select('departments_table', item => item.id === _departmentId)[0];
    const newDepart = db.select('departments_table', item => item.id === departmentId)[0];
    console.log(oldDepart,newDepart);
    
    if(JSON.stringify(oldDepart) !== "{}") {
      const {members:oldmembers} = oldDepart;
      db.put('departments_table', _departmentId, {members: oldmembers-1})
    }
    const {members:newmembers} = newDepart;
    db.put('departments_table', departmentId, {members: newmembers+1})
  }
  return {
    code: 0,
    message: '修改成功'
  }
})

// 删除用户
Mock.mock('/users/delete', 'post', ({ body }) => {
  const { ids } = JSON.parse(body);
  if(ids.length == 0) {
    return {
      code: 1005,
      message: '至少选择一个用户'
    }
  }
  db.delete('users_table', ids)
  return {
    code: 0,
    message: '删除成功'
  }
})

// 修改密码
Mock.mock('/users/password','post', ({ body }) => {
  let { id,password, newPassword } = JSON.parse(body);
  id = +id;
  const result = db.select('users_table', item => item.id === id)[0];
  const { userName, password: _password } = result;
  // 判断用户是否存在
  if (!result) {
    return {
      code: 1006,
      message: '用户不存在'
    }
  }
  if(password && newPassword) {
    if( password !== _password ) {
      return {
        code: 1007,
        message: '原密码错误'
      }
    }
    else if ( newPassword == _password ) {
      return {
        code: 1008,
        message: '新密码不能是原旧密码'
      }
    }
  }
  // 如果写了密码就修改,没写就重置密码
  const row = {password: newPassword?newPassword:md5(`${userName}123456`)}
  db.put('users_table', id, row)
  return {
    code: 0,
    message: '修改成功'
  }
})

// 修改状态
Mock.mock('/users/status','post', ({ body }) => {
  let { id, status } = JSON.parse(body);
  id = +id;
  status = +status;
  const result = db.select('users_table', item => item.id === id)[0];
  // 判断用户是否存在
  if (!result) {
    return {
      code: 1006,
      message: '用户不存在'
    }
  }
  const row = {status}
  db.put('users_table', id, row)
  return {
    code: 0,
    message: '修改成功'
  }
})

